package com.itlong.cloud.smartcard.service.impl;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardOldGetProjectPageDTO;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardOldProjectInfoDTO;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardOldUpdateProjectDTO;
import com.itlong.cloud.POJO.PO.AppUserProjectPO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.VO.smartcard.SmartCardOldProjectInfoPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.AppUserProjectStatusEnum;
import com.itlong.cloud.enumerate.AppUserProjectTypeEnum;
import com.itlong.cloud.smartcard.dao.ISmartCardOldProjectDao;
import com.itlong.cloud.smartcard.service.ISmartCardOldProjectService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <desc>
 *      旧一卡通_项目模块服务接口实现类。
 * <desc/>
 *
 * @createDate 2017/11/21.
 */
@Service
@RefreshScope
public class SmartCardOldProjectServiceImpl implements ISmartCardOldProjectService{

    //旧一卡通项目
    @Autowired
    ISmartCardOldProjectDao iSmartCardOldProjectDao;

    ///旧一卡通添加项目的服务器地址IP：端口
    @Value("${"+PlatformConstants.SERVICE_PATH_URL+"}")
    String servicePath;

    //云对讲业务服务器默认地址
    @Value("${" + PlatformConstants.CLOUD_INTERCOM_BUSINESS_SERVER_DEFAULT_URL + "}")
    String defaultBusinessServerUrl;

    /**
     * <desc>
     *      旧一卡通_增加项目信息。
     * <desc/>
     *
     * @param  saveDTO 保存
     * @return
     * @author shengen.T
     * @createDate 2017/11/20
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer addProjectInfo(SmartCardOldProjectInfoDTO saveDTO) throws Exception{
         Integer result = 0;
        //判断项目编号
        ProjectPO projectInfoById = iSmartCardOldProjectDao.selectProjectId(saveDTO.getProjectId());
        Integer projectNameCount =iSmartCardOldProjectDao.selectProjectNameCount(saveDTO.getProjectName());
        if(projectInfoById==null){
            //判断项目名称
            if(projectNameCount>0){
                return result; //存在该项目
            }
            System.out.println("---一卡通添加小区--0--------/manage/add------ProjectInfo:"+ JSON.toJSONString(projectInfoById));
            //添加项目
            ProjectPO projectPO = getProjectPo(saveDTO);
            iSmartCardOldProjectDao.saveProject(SqlUtil.durableData(projectPO,PlatformConstants.TABLE_SAVE));
        }else{
            if (!projectInfoById.getProjectName().equals(saveDTO.getProjectName())) {
                if (projectNameCount>0) {
                    return result;  //存在该项目
                }
            }
            projectInfoById.setProjectName(saveDTO.getProjectName());
            projectInfoById.setProjectMemo(saveDTO.getProjectMemo());
            Integer status = (saveDTO.getProjectStatus()==1)?2:1;
            projectInfoById.setStatus(status);
            projectInfoById.setCreateTime(new Date());
            if(StringUtils.isBlank(projectInfoById.getCountryId())){
                projectInfoById.setCountryId("100000");
            }
            if (StringUtils.isNotEmpty(saveDTO.getProvince())) {
                projectInfoById.setProvinceId(iSmartCardOldProjectDao.selectIdByName(saveDTO.getProvince()));
            }
            if (StringUtils.isNotEmpty(saveDTO.getCity())) {
                projectInfoById.setCityId(iSmartCardOldProjectDao.selectIdByName(saveDTO.getCity()));
            }
            if (StringUtils.isNotEmpty(saveDTO.getDistrict())) {
                projectInfoById.setDistrictId(iSmartCardOldProjectDao.selectIdByName(saveDTO.getDistrict()));
            }
            if (StringUtils.isBlank(projectInfoById.getServerUrl())&&(projectInfoById.getIsPrivateCloud()!=1)) {
                projectInfoById.setIsPrivateCloud(0);
                projectInfoById.setServerUrl(servicePath);
                //未启用私有云时使用默认云对讲业务服务器
                projectInfoById.setDeviceAddress(defaultBusinessServerUrl);
            }
            if (projectInfoById.getIsSmartCommunity()==null) {
                projectInfoById.setIsSmartCommunity(0);
            }
            if ((projectInfoById.getAuthMaxNum()==null)||(projectInfoById.getAuthMaxNum()==0)) {
                projectInfoById.setIsSmartCommunity(10);
            }
            System.out.println("---一卡通添加小区--1--------/manage/add------ProjectInfo:"+JSON.toJSONString(projectInfoById));
            iSmartCardOldProjectDao.updateProject(SqlUtil.durableData(projectInfoById,PlatformConstants.TABLE_UPDATE));
        }
        result = 1;  //添加项目成功
        return result;
    }

    /**
     * <desc>
     *      获取项目列表。
     * <desc/>
     *
     * @param  pageDTO 请求参数
     * @return
     * @author shengen.T
     * @createDate 2017/11/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Page<SmartCardOldProjectInfoPageVO> getProjectInfoPage(SmartCardOldGetProjectPageDTO pageDTO) throws Exception{
        Integer pageCount = 0;
        //分页对象
        Page<SmartCardOldProjectInfoPageVO> page = new Page<>();
        //查询
        List<SmartCardOldProjectInfoPageVO> projectVOS = iSmartCardOldProjectDao.getProjectInfoList(pageDTO.getProjectId());
        if((projectVOS!=null)&&(projectVOS.size()>0)){
            pageCount = 1;
        }
        //填充返回数据集
        page.setRows(projectVOS, pageCount);
        return page;
    }



    /**
     * <desc>
     *      修改项目。
     * <desc/>
     *
     * @param  updateDTO
     * @return  返回影响行数
     * @author shengen.T
     * @createDate 2017/11/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateProjectInfo(SmartCardOldUpdateProjectDTO updateDTO) throws Exception{
        Integer result=0;
        //判断项目编号
        ProjectPO projectInfoById = iSmartCardOldProjectDao.selectProjectId(updateDTO.getProjectId());
        if((projectInfoById!=null)&&(!StringUtils.isBlank(projectInfoById.getProjectId()))){
            ProjectPO projectPO = new ProjectPO();
            projectPO.setProjectId(updateDTO.getProjectId());
            Integer prjNameCount =iSmartCardOldProjectDao.selectProjectNameCount(updateDTO.getProjectName());
            if(prjNameCount>0){
                if(!StringUtils.isBlank(projectInfoById.getProjectName())
                        && !projectInfoById.getProjectName().equals(updateDTO.getProjectName())){
                    return result;  //小区重名
                }
            }
            projectPO.setProjectName(updateDTO.getProjectName());
            projectPO.setPubKey(updateDTO.getPubKey());
            projectPO.setProjectMemo(updateDTO.getProjectMemo());
            projectPO.setUpdateTime(new Date());
            if(StringUtils.isBlank(projectInfoById.getCountryId())){
                projectPO.setCountryId("100000");
            }
            projectPO.setProvinceId(iSmartCardOldProjectDao.selectIdByName(updateDTO.getProvince()));
            projectPO.setProvinceId(iSmartCardOldProjectDao.selectIdByName(updateDTO.getProvince()));
            projectPO.setCityId(iSmartCardOldProjectDao.selectIdByName(updateDTO.getCity()));
            projectPO.setDistrictId(iSmartCardOldProjectDao.selectIdByName(updateDTO.getDistrict()));
            Integer count = iSmartCardOldProjectDao.updateProject(SqlUtil.durableData(projectPO,PlatformConstants.TABLE_UPDATE));
            if(count>0) {
                Integer userPrjCount = iSmartCardOldProjectDao.selectUserProjectCount("admin", updateDTO.getProjectId());
                AppUserProjectPO userPrjtPO = getUserProjectPO(updateDTO.getProjectId());
                if (userPrjCount > 0) {

                    userPrjtPO.setUpdateTime(new Date());
                    iSmartCardOldProjectDao.updateUserProject(userPrjtPO);
                } else {
                    iSmartCardOldProjectDao.saveUserProject(SqlUtil.durableData(userPrjtPO, PlatformConstants.TABLE_SAVE));
                }
            }
            return count;
        }else{
           result =2;  //不存在该项目信息
           return result;
        }
    }

    /**
     * <desc>
     *      获取项目信息对象。
     * <desc/>
     *
     * @param  saveDTO 请求参数
     * @return
     * @author shengen.T
     * @createDate 2017/11/20
     */
    private ProjectPO getProjectPo(SmartCardOldProjectInfoDTO saveDTO){
        ProjectPO projectPO = new ProjectPO();
        projectPO.setProjectId(saveDTO.getProjectId());
        projectPO.setProjectName(saveDTO.getProjectName());
        projectPO.setCommunityName(saveDTO.getProjectName());
        projectPO.setProjectMemo(saveDTO.getProjectMemo());
        projectPO.setPubKey(saveDTO.getPubKey());
        projectPO.setProvinceId(iSmartCardOldProjectDao.selectIdByName(saveDTO.getProvince()));
        projectPO.setCityId(iSmartCardOldProjectDao.selectIdByName(saveDTO.getCity()));
        projectPO.setDistrictId(iSmartCardOldProjectDao.selectIdByName(saveDTO.getDistrict()));

        projectPO.setAuthMaxNum(10);
        projectPO.setCreateTime(new Date());
        projectPO.setIsPrivateCloud(0);
        projectPO.setCountryId("100000");
        if(NumberHandlerUtil.isEqual(0, projectPO.getIsPrivateCloud())){
            Integer status = (saveDTO.getProjectStatus()==1)?2:1;
            projectPO.setStatus(status);
        }
        projectPO.setIsSmartCommunity(0);
        projectPO.setServerUrl(servicePath);
        return projectPO;
    }

    /**
     * <desc>
     *      获取用户项目关系对象。
     * <desc/>
     *
     * @param  projectId
     * @return userProjectPO
     * @author shengen.T
     * @createDate 2017/11/20
     */
    private AppUserProjectPO getUserProjectPO(String projectId){
        AppUserProjectPO userProjectPO = new AppUserProjectPO();
        userProjectPO.setUserId("admin");
        userProjectPO.setProjectId(projectId);
        userProjectPO.setUserProjectStatus(AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_ENABLE.getType().toString());
        userProjectPO.setProjectType(AppUserProjectTypeEnum.USERPROJECT_TYPE_SELF.getType().toString());
        userProjectPO.setUserType(1);
        userProjectPO.setStatus(1);
        userProjectPO.setCreateTime(new Date());
        return userProjectPO;
    }
}
